import MD5 from 'js-md5'
import Vue from 'vue'
import store from '../store'
import StringUtils from '../utils/StringUtils'

let xtoken_key = 'sd11XTOKENsioSKDJh9822nfFHajj33_nw'

let Base64 = require('js-base64').Base64;
//apiKey 更新时间间隔 -- 5分钟
let apiKeyUpdateTime = 1000 * 60 * 5;

export default {
    init() {
        // return true
        // //激活一下
        let xTokenParams = getXTokenParams();
        let refreshXTokenTimer;
        if (!!refreshXTokenTimer) {
            clearInterval(refreshXTokenTimer)
        }
        //计时器刷新xtoken参数
        refreshXTokenTimer = setInterval(refreshXTokenParams, apiKeyUpdateTime);
        return !!xTokenParams
    },
    get() {
        // return {}
        let xtokenParams = getXTokenParams();
        let apiKeyInfo = xtokenParams.apiKeyInfo;
        //当前时间，要加上与服务器的时间差
        let nowTime = Date.parse(new Date());
        let time = nowTime + apiKeyInfo.timeDifference;
        let token = genToken(xtokenParams.userId, xtokenParams.deviceType, xtokenParams.deviceId, apiKeyInfo.version, apiKeyInfo.apiKey, time);
        let randomCode = Math.random().toString(36).substr(2).slice(1, 6);
        let baseParams = xtokenParams.userId + '#' + xtokenParams.deviceType + '#' + xtokenParams.deviceId
            + '#' + apiKeyInfo.version + '#' + time + '#' + randomCode;
        // console.log("token : " + token)
        return {
            baseParams: baseParams,
            token: token,
            apiKey: MD5(apiKeyInfo.apiKey)
        };
    },
    getDeviceId() {
        return getDeviceId()
    }
}

/**
 * 获得xtoken参数
 */
function getXTokenParams() {
    let xtokenParams = JSON.parse(window.decodeURIComponent(localStorage.getItem(xtoken_key)));
    if (!xtokenParams || (Date.parse(new Date()) - xtokenParams.refreshTime > apiKeyUpdateTime)) {
        xtokenParams = refreshXTokenParams();
    }
    return xtokenParams
}

/**
 * 刷新xtoken参数
 */
function refreshXTokenParams() {
    let deviceType = 2;
    let deviceId = getDeviceId();
    let version = process.env.VERSION;
    let userId = getUserId();
    let apiKeyInfo = getApiKeyInfo(userId, deviceType, deviceId);
    let tokenParams = {
        userId: userId,
        deviceType: deviceType,
        deviceId: deviceId,
        apiKeyInfo: apiKeyInfo,
        refreshTime: Date.parse(new Date())
    };
    localStorage.setItem(xtoken_key, window.encodeURIComponent(JSON.stringify(tokenParams)));
    return tokenParams;
}

/**
 * 获得设备号deviceId
 * @returns {null}
 */
function getDeviceId() {
    let deviceIdName = 'deviceId';
    let deviceId = localStorage.getItem(deviceIdName) ? JSON.parse(localStorage.getItem(deviceIdName)) : null;
    if (!deviceId) {
        deviceId = StringUtils.randomStr(5) + Date.parse(new Date()) + StringUtils.randomStr(5);
        localStorage.setItem(deviceIdName, JSON.stringify(deviceId));
    }
    return deviceId;
}

/**
 * 获得userId
 * @returns {null}
 */
function getUserId() {
    let userId = 0;
    let currentUser = store.getters.currentUserFn;
    if (!!currentUser && currentUser != 'null' && currentUser.userId) {
        userId = currentUser.userId;
    }
    if (userId) {
        return userId;
    }
    return 0
}

/**
 * 获得api key信息
 */
function getApiKeyInfo(userId, deviceType, deviceId) {
    let url = Vue.prototype.NW_API_TOKEN + "/web/version?userId=" + userId +
        "&deviceType=" + deviceType + "&deviceId=" + deviceId;
    let apiKeyInfo;
    console.log(url);
    $.ajax({
        type: "GET",
        url: url,
        async: false,
        dataType: 'json',
        success: function (res) {
            if (res.success) {
                apiKeyInfo = {
                    version: res.result.version,
                    apiKey: res.result.apiKey,
                    timeDifference: res.result.currentTime - Date.parse(new Date())
                };
            } else {
                console.log("getApiKeyInfo error : " + JSON.parse(res))
            }
        },
        fail(data) {
            console.log(JSON.stringify(data))
        }
    })
    return apiKeyInfo;
}

/**
 * 生成token
 * @returns
 */
function genToken(userId, deviceType, deviceId, version, apiKey, time) {
    let md5Content = Base64.encode(userId) + '' + Base64.encode(deviceType) + ''
        + deviceId + '' + version + '' + '' + apiKey;
    return MD5(md5Content);
}

/**
 * 刷新头部
 * @returns
 */
function refreshHeader() {
    let md5Content = Base64.encode(userId) + '' + Base64.encode(deviceType) + ''
        + deviceId + '' + version + '' + '' + apiKey;
    return MD5(md5Content);
}
